package com.tenchael.http.controller;

import static com.tenchael.http.commons.Constants.LOGIN_PAGE;
import static com.tenchael.http.commons.Constants.LOGIN_USER;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tenchael.http.domain.User;
import com.tenchael.http.service.UserService;

@Controller(value = "home_controller")
@RequestMapping("/")
public class HomeController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = { "/", "index", "home", "welcome" }, method = RequestMethod.GET)
	@ResponseBody
	private String home(HttpServletRequest request) {
		return "Hello";
	}

	@RequestMapping(value = "login", method = RequestMethod.GET)
	private String loginView(HttpServletRequest request) {
		return LOGIN_PAGE;
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password, HttpServletRequest request) {
		User user = new User(username, password);
		User userData = userService.login(user);

		if (userData == null) {
			return "login";
		} else {
			request.getSession().setAttribute(LOGIN_USER, userData);
			return "redirect:/home";
		}
	}

}
